<template>
  <div class="login">
    <el-form label-position="top" label-width="80px" :model="formLabelAlign"
    :rules="rules" ref="formLabelAlign">
      <h2>登录</h2>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="formLabelAlign.phone"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="formLabelAlign.password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm()" :loading="loading">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
// eslint-disable-next-line
import { Login } from '@/services/user';
import store from '@/store';

export default {
  name: 'loginCompnent',
  created() {
    store.commit('setUser', null);
  },
  data() {
    return {
      formLabelAlign: {
        phone: '18201288771',
        password: '111111',
      },
      rules: {
        phone: [
          {
            required: true, pattern: /^1[34578][0-9]{9}$/, message: '请输入正确的手机号', trigger: 'blur',
          },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'change' },
          {
            min: 6, max: 8, message: '长度在 6 到 8 个字符', trigger: 'blur',
          },
        ],
      },
      loading: false,
    };
  },
  methods: {
    async submitForm() {
      try {
        await this.$refs.formLabelAlign.validate((valid) => {
          if (!valid) {
            throw new Error('error submit');
          }
          return true;
        });
        this.loading = true;
        const { data } = await Login(this.formLabelAlign);
        if (data.state === 1) {
          this.$store.commit('setUser', data.content);
          this.$router.push(this.$route.query.redirect || { name: 'Home' });
          this.$message.success('登录成功');
        } else {
          this.$message.error('登陆失败');
        }
        this.loading = false;
      } catch (error) {
        console.log('校验未通过');
      }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>

<style scoped>
.login {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #e9eef3;
}
.login .el-form {
  width: 400px;
  background: #fff;
  padding: 20px;
  border-radius: 15px;
}
.login .el-form .el-button {
  width: 100%;
}
</style>
